package handler

import (
	"fmt"
	"net/http"
	"src/gcommon"
	"src/zeus/logger"
	"time"

	"github.com/gin-gonic/gin"
)

func GetRouter() *gin.Engine {
	if !gcommon.GetCfgInst().Config.Debug {
		gin.SetMode(gin.ReleaseMode)
	}
	gin.DefaultWriter = logger.NewLoggerIO(logger.LogLevelDebug, logger.LogKey_GinHttp)
	gin.DefaultErrorWriter = logger.NewLoggerIO(logger.LogLevelError, logger.LogKey_GinHttp)
	router := gin.New()
	router.Use(GinLogger, gin.Recovery())
	router.Any("ping", func(ctx *gin.Context) {
		ctx.JSON(http.StatusOK, gin.H{})
	})
	// 注册
	router.POST("RegisterReq", OnRegisterReq)
	// 登录
	router.POST("LoginReq", OnLoginReq)

	// // 得到所有服务器列表
	// router.POST("getGroupList", srvGroupHandler)
	// // 登录创建号
	// if gcommon.GetCfgInst().Config.Debug {
	// 	pprof.Register(router)
	// 	// router.GET("/debug/pprof/", gin.WrapF(http.DefaultServeMux.ServeHTTP))
	// 	router.POST("userLoginNew", userLoginNewHandler)
	// }
	// router.POST("youkaLogin", youkaLoginHandler)
	// router.POST("youkaLoginNew", youkaLoginNewHandler)

	// //> 玩家拿到token后的http请求,服务器的uid应该都从head中解析拿出
	// loginAfter := router.Group("loginAfter", verifyHandler)

	// //返回玩家已有角色的服务器信息
	// loginAfter.POST("getOwnerGroupList", alreadyHaveHandler)

	// // 选择服务器,返回这个服务器下的所有角色
	// loginAfter.POST("pickGroup", pickGroupHandler)
	// // 创角
	// loginAfter.POST("createRole", createRoleHandler)
	// // 选择角色进游戏
	// loginAfter.POST("ChooseHeroHandler", ChooseHandler)
	// // 绕过sdk进入游戏
	// router.POST("GodChooseHeroReq", GodChooseHandler)
	// //删除角色
	// loginAfter.POST("DeleteHeroHandler", DeleteHandler)
	// loginAfter.POST("getGroupList", srvGroupNewHandler)

	return router
}

func GinLogger(c *gin.Context) {
	if !logger.CheckKey(logger.LogKey_GinHttp) {
		c.Next()
		return
	}
	//客户端刷新太频繁,所以屏蔽日志
	//if strings.Contains(c.Request.URL.Path, "/getGroupList") {
	//	c.Next()
	//	return
	//}

	// Start timer
	start := time.Now()
	path := c.Request.URL.Path
	raw := c.Request.URL.RawQuery
	// Process request
	c.Next()
	out := gin.DefaultWriter
	// Log only when path is not being skipped
	n := time.Now()
	tmp := n.Sub(start)
	if raw != "" {
		path = path + "?" + raw
	}
	log := fmt.Sprintf("| %3d | %15s |%s %s %#v\n%s",
		c.Writer.Status(),
		tmp,
		c.ClientIP(),
		c.Request.Method,
		path,
		c.Errors.ByType(1).String())
	out.Write([]byte(log))
	//fmt.Fprint(out)
}
